var express = require('express');
var router = express.Router();
var  crypto = require('crypto');
var  User   = require('../models/user.js');
var  Post = require('../models/postArticle.js');


/* GET home page. */
// router.get('/',checkNotLogin);
router.get('/', function(req, res, next) {


    var name ;
    if (req.session.user != null){
        if (req.session.user.name != null){

            name = req.session.user.name;
        }else {
            name = null;
        }
    }else {

        name = null;
    }
    Post.get(name,function (err,posts) {

        if (err){
            posts = [];
        }
        res.render('index', { title   : '主页' ,
            user    : req.session.user,
            posts   : posts,
            success : req.flash('success').toString(),
            error   : req.flash('error').toString()});

    });

});

//用户未登录校验
router.get('/reg',checkNotLogin);
router.get('/reg',function (req,res) {


  res.render('reg',{ title   : '注册' ,
                     user    : req.session.user,
                     success : req.flash('success').toString(),
                     error   : req.flash('error').toString()});

});

//用户未登录校验
router.get('/login',checkNotLogin);
router.get('/login',function (req,res) {


    res.render('login',{ title   : '登录' ,
                         user    : req.session.user,
                         success : req.flash('success').toString(),
                         error   : req.flash('error').toString()});

});

//用户未登录校验
router.post('/reg',checkNotLogin);
router.post('/reg',function (req,res) {


    var name = req.body.name;
    var password = req.body.password;
    var password_re = req.body['password-repeat'];
    //检验用户两次输入的密码是否一致
    if (password_re != password){

        req.flash('error','两次输入的密码不一致!');
        return res.redirect('/reg');
    }

    //生成密码的MD5值
    var md5 = crypto.createHash('md5');
    var  password = md5.update(req.body.password).digest('hex');
    var  newUser = new  User({

        name :name,
        password:password,
        email:req.body.email

    });


    User.get(newUser.name,function (err, user) {
       if (err){

           console.log('出现错误!');
           req.flash('error',err);
           return res.redirect('/');

       }

       if (user){

           console.log('用户已经存在!');
           req.flash('error','用户已经存在!');
           return res.redirect('/reg');
       }
       //如果不存在则新增用户
        newUser.save(function (err,user) {

            if (err){
                req.flash('error',err);
                return res.redirect('/reg');
            }
            req.session.user = newUser;
            req.flash('success','注册成功!');
            res.redirect('/');//注册成功返回主页
        });

    });

});

router.post('/login',checkNotLogin);
router.post('/login',function (req,res) {

    //生成的密码MD5

    var md5 = crypto.createHash('md5');
    var  password = md5.update(req.body.password).digest('hex');


    // var md5 = crypto.createHash('md5');
    // var  password = md5.update(req.boby.password).digest('hex');

    //检查用户是否存在
    User.get(req.body.name,function (err,user) {

        if (!user){

            req.flash('error','用户不存在!');
            return res.render('/login');//用户不存在跳转登录页
        }

        //检查密码是否一致
        if (user.password != password){

            req.flash('error','密码错误');
            return res.redirect('/login');//密码错误跳转到登录页
        }

        //用户名与密码都匹配后,用户信息存入sesssion
        req.session.user = user;
        req.flash('success','登陆成功');
        res.redirect('/');

    });

});

router.get('/postArticle',function (req,res) {

    res.render('postArticle', {
        title: '发表',
        user    : req.session.user
        // success : req.flash('success').toString(),
        // error   : req.flash('error').toString()
    });
});


router.post('/post',checkLogin);
router.post('/postArticle',function (req,res) {

    var curenterUser = req.session.user;
    var post = new  Post(curenterUser.name, req.body.title,req.body.post);
    post.save(function (err) {

        if (err){

            req.flash('error',err);

            return res.redirect('/');
        }

        req.flash('success','发布成功');
        res.redirect('/');

    });

});

router.get('/logout',checkLogin);
router.get('/logout',function (req,res) {

    req.session.user = null;
    req.flash('success','登出成功!');
    res.redirect('/');

});

function checkLogin(req,res,next) {

    if (!req.session.user ){
        req.flash('error','未登录');
        res.redirect('/login');
    }
    next();
}

function checkNotLogin(req,res,next) {

    if (req.session.user && req.url !== '/reg'){
        req.flash('error','已登录!');
        res.redirect('/postArticle');
    }
    next();

}

module.exports = router;
